# -*- coding: utf-8 -*-

"""
深度学习处理；
"""
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from dvadmin.system.models import AiStudy
from dvadmin.utils.serializers import CustomModelSerializer
from dvadmin.utils.viewset import CustomModelViewSet
from dvadmin.utils.json_response import DetailResponse, SuccessResponse, ErrorResponse
from django.shortcuts import render
from django.conf import settings
import zipfile
import os


class AiStudySerializer(CustomModelSerializer):
    """
    学习进度-序列化器
    """

    class Meta:
        model = AiStudy
        fields = "__all__"
        read_only_fields = ["id"]


class AiStudyViewSet(CustomModelViewSet):
    """
    学习进度接口
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    queryset = AiStudy.objects.all()
    serializer_class = AiStudySerializer
    extra_filter_class = []

    # 启动学习
    @action(methods=['post'], detail=False, permission_classes=[IsAuthenticated], )
    def startStudy(self, request, *args, **kwargs):
        isStudying = True
        # params = request.query_params.get("url")
        zipFilePath = request.data.get("url")

        # 解压文件，解压到：extract_folder
        extract_folder = zipFilePath.split('.')[0]
        zip_file = zipfile.ZipFile(zipFilePath, "r")
        zip_file.extractall(path=extract_folder)
        zip_file.close()  # 关闭

        # TODO 启动学习;

        return SuccessResponse(data=zipFilePath, msg="启动学习成功")

    # 测试结果;
    @action(methods=['post'], detail=False, permission_classes=[IsAuthenticated], )
    def testStudy(self, request, *args, **kwargs):
        # inputText = request.data.get("inputText")
        retText = "学习生成了，生成摘要如下：你好，南京！"
        return SuccessResponse(data=retText, msg="生成成功")

    # 测试结果;
    @action(methods=['post'], detail=False, permission_classes=[IsAuthenticated], )
    def config(self, request, *args, **kwargs):
        # 数据集; 1:lcsts_data, 2:农业新闻,
        dataValue = request.data.get("dataValue")
        # 模型; 1:ERNIE, 2:UniLM, 3:Nezha
        modalValue = request.data.get("modalValue")
        # 配置参数;
        configTxt = request.data.get("configTxt")

        return SuccessResponse(data=True, msg="设置成功")
